package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Login;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;

@RestController
@Slf4j
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/login")
    public Result login(@RequestBody Login login){
        //从Redis中获取缓存的验证码
        String codeOfRedis = redisTemplate.opsForValue().get(login.getTelephone() + RedisMessageConstant.SENDTYPE_LOGIN);
        if (codeOfRedis == null || !codeOfRedis.equals(login.getValidateCode())){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else {
            // 验证码正确
            // 判断是否为会员
            Member member = memberService.findByTelephone(login.getTelephone());
            if (member == null){
                // 不是会员，，自动注册
                member = new Member();
                member.setPhoneNumber(login.getTelephone());
                member.setRegTime(new Date());
                memberService.add(member);
            }
        }
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
